package com.example.springsecurity.common.aop.aspect;

import cn.hutool.json.JSONUtil;
import com.example.springsecurity.common.annotation.SystemLogInterface;
import com.example.springsecurity.common.enums.DelStatusEnums;
import com.example.springsecurity.common.enums.StatusEnums;
import com.example.springsecurity.common.utils.IpUtil;
import com.example.springsecurity.common.utils.SecurityUtil;
import com.example.springsecurity.common.utils.ServletUtils;
import com.example.springsecurity.entity.SystemOperationLog;
import com.example.springsecurity.entity.SystemUser;
import com.example.springsecurity.service.SystemOperationLogService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerMapping;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.Map;

/**
 * @Description：系统日志切面类
 * @Author：fengcheng
 * @Date：2025/1/17 10:23
 */
@Slf4j
@Aspect
@Component
@RequiredArgsConstructor
public class WebLogAspect {

    private final SystemOperationLogService systemOperationLogService;

    /**
     * @Description：系统日志切入点，凡是使用到【@SystemLogInterface】注解的方法，都会被拦截
     * @Author：fengcheng
     * @Date：2025/1/17 10:23
     * @Return：void
     */
    @Pointcut("@annotation(com.example.springsecurity.common.annotation.SystemLogInterface)")
    public void logPointCut() {}

    /**
     * @Description：被切入的方法执行完成后，进入到此通知
     * @Author：fengcheng
     * @Date：2025/1/17 10:25
     * @Param：joinPoint
     * @Param：jsonResult
     * @ParamsType：[org.aspectj.lang.JoinPoint, java.lang.Object]
     * @Return：void
     */
    @AfterReturning(pointcut = "logPointCut()", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) {
        handleLog(joinPoint, null, jsonResult);
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e         异常
     */
    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
        handleLog(joinPoint, e, null);
    }

    protected void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult) {
        try {
            // 获得注解
            SystemLogInterface controllerLog = getAnnotationLog(joinPoint);
            if (ObjectUtils.isEmpty(controllerLog)) {
                return;
            }
            // 获取当前的用户
            SystemUser loginUser = SecurityUtil.getSystemUser();
            // *========数据库日志=========*//
            SystemOperationLog operLog = new SystemOperationLog();
            operLog.setStatus(Integer.valueOf(StatusEnums.ENABLE.getCode()));
            operLog.setDeleted(DelStatusEnums.DISABLE.getCode());
            // 请求的地址
            String ip = IpUtil.getIp(ServletUtils.getRequest());
            operLog.setReqIp(ip);
            // 返回参数
            operLog.setResp(JSONUtil.toJsonStr(jsonResult));
            if (ObjectUtils.isNotEmpty(loginUser)) {
                operLog.setOperName(loginUser.getUsername());
            }
            if (ObjectUtils.isNotEmpty(e)) {
                operLog.setStatus(Integer.valueOf(StatusEnums.DISABLE.getCode()));
                operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
            }
            // 设置方法名称
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            operLog.setMethod(className + "." + methodName + "()");
            // 设置请求方式
            operLog.setRequestMethod(ServletUtils.getRequest().getMethod());
            operLog.setCreateBy(loginUser.getUsername());
            operLog.setCreateTime(new Date());
            // 处理设置注解上的参数
            getControllerMethodDescription(joinPoint, controllerLog, operLog);
            // TODO 保存数据库 需要处理成异步
			// AsyncManager.me().execute(AsyncFactory.recordOper(operLog));
            systemOperationLogService.save(operLog);
        } catch (Exception exp) {
            // 记录本地异常日志
            log.error("接口执行异常，异常信息:{}", exp.getMessage(), e);
        }
    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param log             日志
     * @param systemOperationLog 操作日志
     */
    public void getControllerMethodDescription(JoinPoint joinPoint, SystemLogInterface log, SystemOperationLog systemOperationLog) {
        // 设置action动作
        systemOperationLog.setBusinessType(log.businessType().getCode());
        // 设置标题
        systemOperationLog.setDescription(log.title());
        // 是否需要保存request，参数和值
        if (log.isSaveRequestData()) {
            // 获取参数的信息，传入到数据库中。
            setRequestValue(joinPoint, systemOperationLog);
        }
    }

    /**
     * 获取请求的参数，放到log中
     *
     * @param systemOperationLog 操作日志
     */
    private void setRequestValue(JoinPoint joinPoint, SystemOperationLog systemOperationLog) {
        String requestMethod = systemOperationLog.getRequestMethod();
        if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod)) {
            String params = argsArrayToString(joinPoint.getArgs());
            systemOperationLog.setReqParam(StringUtils.substring(params, 0, 2000));
        } else {
            Map<?, ?> paramsMap = (Map<?, ?>) ServletUtils.getRequest().getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
            systemOperationLog.setReqParam(StringUtils.substring(paramsMap.toString(), 0, 2000));
        }
    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private SystemLogInterface getAnnotationLog(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (ObjectUtils.isNotEmpty(method)) {
            return method.getAnnotation(SystemLogInterface.class);
        }
        return null;
    }

    /**
     * 参数拼装
     */
    private String argsArrayToString(Object[] paramsArray) {
        StringBuilder params = new StringBuilder();
        if (ObjectUtils.isNotEmpty(paramsArray)) {
            for (Object o : paramsArray) {
                if (!isFilterObject(o)) {
                    Object jsonObj = JSONUtil.toJsonStr(o);
                    params.append(jsonObj.toString()).append(" ");
                }
            }
        }
        return params.toString().trim();
    }

    /**
     * 判断是否需要过滤的对象。
     *
     * @param o 对象信息。
     * @return 如果是需要过滤的对象，则返回true；否则返回false。
     */
    public boolean isFilterObject(final Object o) {
        return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse;
    }

}
